﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Mimic.Model;

namespace Mimic
{
    /// <summary>
    /// 描述：请求模拟者，负责发送请求与解析相应内容
    /// 创建人：吴鸣震
    /// 创建时间：2009年5月26日
    /// 版本：v 0.1
    /// </summary>
    public class Mimic
    {
        //默认配置项
        public Config Config { get; private set; }
        //cookie容器，保证每个MIMIC代表一个用户
        private readonly CookieContainer __myCookieContainer = new CookieContainer();

        /// <summary>
        /// 私有化构造函数
        /// </summary>
        private Mimic(Config _config)
        {
            Config = _config;
        }

        public static Mimic CreateMimic()
        {
            var config = new Config
                             {
                                 Accept =
                                     "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*",
                                 UserAgent =
                                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; GTB6; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)",
                                 Timeout = 12000,
                                 ContentType = "application/x-www-form-urlencoded"
                             };
            return CreateMimic(config);
        }

        public static Mimic CreateMimic(Config config)
        {
            return new Mimic(config);
        }
        
        #region method
        public Interpreter Get(string url, DataType type, params NameValue[] parameters)
        {
            HttpWebRequest request = CreateHttpWebRequest(url + "?" + MakeQueryString(parameters));
            request.Method = "get";
            Interpreter interpreter = new Interpreter(GetResponse(request.GetResponse())) {DataType = type};
            return interpreter;
        }

        public Interpreter Post(string url, DataType type, params NameValue[] parameters)
        {
            HttpWebRequest request = CreateHttpWebRequest(url);
            request.Method = "post";
            string postData = MakeQueryString(parameters);
            
            if (postData!= string.Empty)
            {
                byte[] data = Encoding.GetEncoding("GB2312").GetBytes(postData);
                request.ContentLength = data.Length;
                Stream s = request.GetRequestStream();
                s.Write(data, 0, data.Length);
                s.Close();   
            }
           
            Interpreter interpreter = new Interpreter(GetResponse(request.GetResponse())) {DataType = type};
            return interpreter;
        }
        #endregion

        #region private method
        private HttpWebRequest CreateHttpWebRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = __myCookieContainer;
            request.Accept = Config.Accept;
            request.UserAgent = Config.UserAgent;
            request.KeepAlive = true;
            request.ProtocolVersion = HttpVersion.Version11;
            request.Timeout = Config.Timeout;
            request.Headers.Add("Accept-Language", "zh-cn");
            request.ContentType = Config.ContentType;
            
            return request;
        }
        private static string GetResponse(WebResponse response)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string result = readStream.ReadToEnd();
            readStream.Close();
            response.Close();
            return result;
        }
        public string MakeQueryString(params NameValue[] parameters)
        {
            StringBuilder sb = new StringBuilder();
            
            foreach (var parameter in parameters)
            {
                sb.Append(parameter.ToString());
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
   
        #endregion
    }
}
